﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;

namespace SoGame.Model
{
    public partial class SoGameDbContext : DbContext
    {
        /// <summary>
        /// Gets the game play to be send.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Tuple<Player, GamePlay, GamePlay>> GetGamePlayToBeSend() {
            var bestGamePlays =
                from g in GamePlays
                group g by new { g.Game, g.PlayerID } into g
                let maxScore = g.Max(x => x.Score)
                let gamePlay = g.FirstOrDefault(x => x.Score == maxScore && ( x.SentMail == null || !x.SentMail.MailSend ))
                //where gamePlay.Game == "SoSlam"
                orderby gamePlay.Score descending
                select gamePlay;

            var bestSoSlamGamePlays = from g in bestGamePlays
                                  where g.Game == "SoSlam"
                                  select g;

            var bestSoTankGamePlays = from g in bestGamePlays
                                      where g.Game == "SoTank"
                                      select g;

            //var tobeSend =
            //    from gSoSlam in bestSoSlamGamePlays
            //    join s in SentMails on gSoSlam.ID equals s.GamePlayID into sm
            //    from gs in sm.DefaultIfEmpty()
            //    let mailSend = gs == null ? false : gs.MailSend
            //    where !mailSend
            //    select gSoSlam;

            var tobeSend = from p in Players
                           select new
                           {
                               Player = p,
                               BestSoSlam = bestSoSlamGamePlays.FirstOrDefault(g => g.PlayerID == p.ID),
                               BestSoTank = bestSoTankGamePlays.FirstOrDefault(g => g.PlayerID == p.ID)
                           };

            var ret = new List<Tuple<Player, GamePlay, GamePlay>>();
            tobeSend.Where(tbs => tbs.BestSoSlam != null || tbs.BestSoTank != null).ToList().ForEach(tbs => ret.Add(new Tuple<Player, GamePlay, GamePlay>(tbs.Player, tbs.BestSoSlam, tbs.BestSoTank)));


            return ret;
        }

        /// <summary>
        /// Updates the sent mail.
        /// </summary>
        /// <param name="sentMail">The sent mail.</param>
        public void UpdateSentMail(SentMail sentMail) {
            this.Entry(sentMail).State = System.Data.EntityState.Modified;
        }

        /// <summary>
        /// Saves the sent mail.
        /// </summary>
        /// <param name="sentMail">The sent mail.</param>
        public void SaveSentMail(SentMail sentMail) {
            this.SentMails.Add(sentMail);
        }


    }
}
